from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from fastapi import Request
from app.core.config import settings
import logging

logger = logging.getLogger(__name__)

class DummyLimiter:
    """在限流器初始化失败时的降级实现（不做限流，仅保留装饰器接口）。"""
    def limit(self, *_args, **_kwargs):
        def decorator(func):
            return func
        return decorator


def _init_limiter():
    try:
        # 标准初始化；某些环境下 Starlette 读取 .env 会因编码报错
        return Limiter(key_func=get_remote_address)
    except Exception as e:
        logger.warning(f"Limiter 初始化失败，已降级为无限流模式: {e}")
        return DummyLimiter()


# 创建限流器（失败则降级为 DummyLimiter，避免 .env 编码问题导致启动失败）
limiter = _init_limiter()

# 限流配置
RATE_LIMITS = {
    "characters_search": "100/minute",  # 角色搜索接口：每分钟最多100次请求
    "characters_chat": "30/minute",     # 对话接口：每分钟最多30次请求
    "default": "200/minute"             # 其他接口：每分钟最多200次请求
}

def get_rate_limit(endpoint_name: str = "default") -> str:
    """获取指定接口的限流配置"""
    return RATE_LIMITS.get(endpoint_name, RATE_LIMITS["default"])
